package net.raebiger.spreadsheetcat.spreadsheet;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import net.raebiger.spreadsheetcat.model.WorksheetDetails;
import android.os.AsyncTask;
import android.util.Log;

import com.google.gdata.client.spreadsheet.FeedURLFactory;
import com.google.gdata.client.spreadsheet.SpreadsheetService;
import com.google.gdata.client.spreadsheet.WorksheetQuery;
import com.google.gdata.data.spreadsheet.CellEntry;
import com.google.gdata.data.spreadsheet.CellFeed;
import com.google.gdata.data.spreadsheet.CustomElementCollection;
import com.google.gdata.data.spreadsheet.WorksheetEntry;
import com.google.gdata.data.spreadsheet.WorksheetFeed;

public class RetrieveWorkbookDetails extends AsyncTask<Void, Void, WorksheetDetails> {
	private final SpreadsheetService service;
	private Exception exception;
	private final String spreadsheetId;
	private CustomElementCollection customElements;

	public RetrieveWorkbookDetails(String authToken, String spreadsheetId) {
		this.service = new SpreadsheetService("SpreadSheetCat");
		this.spreadsheetId = spreadsheetId;
		// Need to hand over the OAuth2 access token to service
		// header
		service.setHeader("Authorization", "Bearer " + authToken);
	}

	@Override
	protected WorksheetDetails doInBackground(Void... params) {
		try {
			// https://spreadsheets.google.com/feeds/worksheets/tWMcsDMZ9ylYx1Iu75sgsIw/private/full
			final URL WORKSHEET_FEED_URL = FeedURLFactory.getDefault().getWorksheetFeedUrl(spreadsheetId, "private",
					"full");

			WorksheetQuery query = new WorksheetQuery(WORKSHEET_FEED_URL);
			WorksheetFeed worksheetFeed = service.query(query, WorksheetFeed.class);
			List<WorksheetEntry> worksheets = worksheetFeed.getEntries();

			// TODO Don't just get first work sheet...
			WorksheetEntry worksheet = worksheets.get(0);

			// get column titles
			URL cellFeedUrlForFirstRow = new URL(worksheet.getCellFeedUrl().toString() + "?min-row=1&max-row=1");
			CellFeed cellFeedForFirstRow = service.getFeed(cellFeedUrlForFirstRow, CellFeed.class);

			ArrayList<String> columnTitles = new ArrayList<String>(cellFeedForFirstRow.getColCount());
			for (CellEntry cell : cellFeedForFirstRow.getEntries()) {
				columnTitles.add(cell.getPlainTextContent());
			}

			// get column types
			// URL cellFeedUrlForSecondRow = new
			// URL(worksheet.getCellFeedUrl().toString() +
			// "?min-row=2&max-row=2");
			// CellFeed cellFeedForSecondRow =
			// service.getFeed(cellFeedUrlForSecondRow, CellFeed.class);
			// for (CellEntry cellEntry : cellFeedForFirstRow.getEntries()) {
			// String kind = cellEntry.getKind();
			// Set<Category> categories = cellEntry.getCategories();
			// for (Category category : categories) {
			// String label = category.getLabel();
			// String labelLang = category.getLabelLang();
			// String scheme = category.getScheme();
			// String term = category.getTerm();
			// }
			// Collection<Extension> extensions = cellEntry.getExtensions();
			// for (Extension extension : extensions) {
			// extension.toString();
			// }
			// int type = cellEntry.getContent().getType();
			// Cell cell = cellEntry.getCell();
			// String inputValue = cell.getInputValue();
			// Number numericValue = cell.getNumericValue();
			// String value = cell.getValue();
			//
			// }

			// get distinct values per column
			// Map<String, Set<String>> distinctValuesPerColumn = new
			// Hashtable<String, Set<String>>();
			// https://spreadsheets.google.com/feeds/list/tWMcsDMZ9ylYx1Iu75sgsIw/od6/private/full
			// ListFeed listFeed = service.getFeed(worksheet.getListFeedUrl(),
			// ListFeed.class);
			// for (ListEntry row : listFeed.getEntries()) {
			// // Print the first column's cell value
			// Log.i("SSC", "ROW: " + row.getTitle().getPlainText());
			// // Iterate over the remaining columns, and print each cell value
			// CustomElementCollection cells = row.getCustomElements();
			// for (String colHeader : columnTitles) {
			// String value = cells.getValue(colHeader);
			// Set<String> distinctValues =
			// distinctValuesPerColumn.get(colHeader);
			// if (distinctValues == null) {
			// distinctValues = new HashSet<String>();
			// distinctValuesPerColumn.put(colHeader, distinctValues);
			// }
			// distinctValues.add(value);
			// }
			//
			// for (String tag : row.getCustomElements().getTags()) {
			// Log.i("SSC", "CELL: " + row.getCustomElements().getValue(tag));
			// }
			//
			// }

			WorksheetDetails worksheetDetails = new WorksheetDetails();
			worksheetDetails.setColumnCount(cellFeedForFirstRow.getColCount());
			worksheetDetails.setColumnTitles(columnTitles);

			return worksheetDetails;
		} catch (Exception e) {
			Log.e("SSC", "Error", e);
			exception = e;
			return null;
		}
	}

	public Exception getException() {
		return exception;
	}

	@Override
	protected void onPostExecute(WorksheetDetails result) {
		Log.d("SSC", "onPostExecute");
	}
}
